package model

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
)

type CvnExamine struct {
	Id          int64 `json:"id" db:"id"`
	Uid         int64 `json:"uid" db:"uid"`
	LogId       int64 `json:"log_id" db:"log_id"`
	Operator    int64 `json:"operator" db:"operator"`
	Status      int   `json:"status" db:"status"`
	ExamineTime int64 `json:"examine_time" db:"examine_time"`
	CreateTime  int64 `json:"create_time" db:"create_time"`
	UpdateTime  int64 `json:"update_time" db:"update_time"`
}

type CvnExamineDetail struct {
	CvnExamine
	Amount   float64 `json:"amount" db:"amount"`
	Nickname string  `json:"nickname" db:"nickname"`
}

type ExamineCheck struct {
	AmountBalance   bool                 `json:"amount_balance"`
	Reconciliation  bool                 `json:"reconciliation"`
	AmountSign      ExamineCheckItem     `json:"amount_sign"`
	LogSign         ExamineCheckItemList `json:"log_sign"`
	LogSourceSymbol ExamineCheckItemList `json:"log_source_symbol"`
	RechargeExist   ExamineCheckItemList `json:"recharge_exist"`
}

type ExamineCheckItemList struct {
	Ok   bool               `json:"ok"`
	List []ExamineCheckItem `json:"list"`
}

type ExamineCheckItem struct {
	Id                 int64  `json:"id,omitempty"`
	Ok                 bool   `json:"ok"`
	OriginalSignString string `json:"original_sign_string,omitempty"`
	CorrectSignString  string `json:"correct_sign_string,omitempty"`
}

//插入记录
func AddCvnExamine(db sqlx.Execer, data CvnExamine) (err error) {
	data.Status = 3
	data.CreateTime = time.Now().Unix()
	data.UpdateTime = time.Now().Unix()
	_, err = db.Exec("INSERT INTO cvn_examine (uid,log_id,status,create_time,update_time) VALUES (?, ?, ?, ?, ?)",
		data.Uid, data.LogId, data.Status, data.CreateTime, data.UpdateTime)
	if err != nil {
		Log("err", err)
	}
	return err
}

//修改记录
func UpdateCvnExamine(db sqlx.Execer, data CvnExamine) (err error) {
	data.ExamineTime = time.Now().Unix()
	data.UpdateTime = time.Now().Unix()
	_, err = db.Exec("UPDATE cvn_examine SET status = ?, operator = ?, examine_time = ?, update_time = ? where id = ?",
		data.Status, data.Operator, data.ExamineTime, data.UpdateTime, data.Id)
	if err != nil {
		Log("err", err)
	}
	return err
}

//获取列表
func GetCvnExamineList(db sqlx.Queryer, page, per, status int, keywords int64, minAmount, maxAmount float64) (qi []CvnExamineDetail, err error) {
	start := (page - 1) * per
	sqlStr := "SELECT t1.id,t1.uid,t1.log_id,t1.operator,t1.status,t1.examine_time,t1.create_time,t1.update_time,-IFNULL(t2.amount,0) as amount,t3.nickname FROM cvn_examine t1 LEFT JOIN cvn_log t2 on log_id = t2.id LEFT JOIN user t3 on t1.uid = t3.uid WHERE 1 = 1 "
	if status > 0 {
		sqlStr += fmt.Sprintf("AND t1.status = %d ", status)
	}
	if keywords > 0 {
		sqlStr += fmt.Sprintf("AND (t3.uid = %d or t3.phone_number = %d) ", keywords, keywords)
	}
	if minAmount > 0 {
		sqlStr += fmt.Sprintf("AND t2.amount <= -%f ", minAmount)
	}
	if maxAmount > 0 {
		sqlStr += fmt.Sprintf("AND t2.amount >= -%f ", maxAmount)
	}
	sqlStr += fmt.Sprintf("ORDER BY t1.id DESC LIMIT %d,%d ", start, per)
	err = sqlx.Select(db, &qi, sqlStr)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}

func GetCvnExamineListCount(db sqlx.Queryer, status int, keywords int64, minAmount, maxAmount float64) (qi int, err error) {
	sqlStr := "SELECT count(*) FROM cvn_examine t1 LEFT JOIN cvn_log t2 on log_id = t2.id LEFT JOIN user t3 on t1.uid = t3.uid WHERE 1 = 1 "
	if status > 0 {
		//获取列表条目总数
		sqlStr += fmt.Sprintf("AND t1.status = %d ", status)
	}
	if keywords > 0 {
		sqlStr += fmt.Sprintf("AND (t3.uid = %d or t3.phone_number = %d) ", keywords, keywords)
	}
	if minAmount > 0 {
		sqlStr += fmt.Sprintf("AND t2.amount <= -%f ", minAmount)
	}
	if maxAmount > 0 {
		sqlStr += fmt.Sprintf("AND t2.amount >= -%f ", maxAmount)
	}
	err = sqlx.Get(db, &qi, sqlStr)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}

//获取单条记录：id
func GetCvnExamine(db sqlx.Queryer, Id int64) (qi CvnExamine, err error) {
	err = sqlx.Get(db, &qi, "SELECT id,uid,log_id,status,operator,examine_time,create_time,update_time FROM cvn_examine WHERE id = ?", Id)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}

//获取单条记录：log_id
func GetCvnExamineByLogId(db sqlx.Queryer, logId int64) (qi CvnExamine, err error) {
	err = sqlx.Get(db, &qi, "SELECT id,uid,log_id,status,operator,examine_time,create_time,update_time FROM cvn_examine WHERE log_id = ?", logId)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}

//是否存在审核中记录
func ExistCvnExamine(db sqlx.Queryer, uid int64) (ok bool, err error) {
	var count int
	err = sqlx.Get(db, &count, "SELECT count(*) FROM cvn_examine WHERE uid = ? AND status = ?", uid, DealStatusCheck)
	if err != nil {
		Log("err", err)
		return false, err
	}
	if count == 0 {
		return false, nil
	}
	return true, nil
}

//查询待审核CVN金额信息
//Auth:Xu
func GetSumUnexamineAmount() (count float64, err error) {
	err = sqlx.Get(config.C.DB.DB, &count, "select ifnull(-sum(l.amount),0) from cvn_examine e INNER JOIN cvn_log l ON e.log_id = l.id AND e.`status` = 3")
	if err != nil {
		Log("err", "查询待审核金额信息失败:", err.Error())
	}
	return
}

//查询累计放行cvnt金额
func GetSumEexamineAmount() (count float64, err error) {
	err = sqlx.Get(config.C.DB.DB, &count, "select ifnull(-sum(l.amount),0) from cvn_examine e INNER JOIN cvn_log l ON e.log_id = l.id AND e.`status` = 1")
	if err != nil {
		Log("err", "查询待审核金额信息失败:", err.Error())
	}
	return
}
